#!/bin/sh

#
# Copyright xgliu515@gmail.com
#

LIBPATH="/lib /lib64 /usr/lib"

function debug
{
	#echo "$*"
	return
}


function findlink
{
	lib=$1;
	linkflag="0";
	findflag="0";
	
	if [ -h $lib ]; then 
		linkflag="1";

		linklib=`ls -l $lib | cut -d ">" -f 2 | sed "s/^\ *//g"`;
		debug  "$lib is link to $linklib"

		if echo $linklib | grep "\.so" > /dev/null; then
			findflag="1";

			if ! echo $linklib | grep "^/" > /dev/null; then
				linklib=`dirname $lib`/$linklib
			fi
		fi
	fi

	if [ ! -e $rootfs/$lib ]; then
		dir=`dirname $lib`
		if [ ! -d $rootfs/$dir ]; then
			debug "mkdir $rootfs/$dir"
			mkdir -p $rootfs/$dir;
		fi

		if [ "$linkflag" -eq "1" ]; then 
			debug "copy link lib $lib to $rootfs/$lib"
			cp -P $lib $rootfs/$lib;
		else
			debug "cp $lib to $rootfs/$dir"
			cp $lib $rootfs/$dir;
		fi
	fi

	if [ "$findflag" -eq "1" ]; then
		debug "contine findlink $linklib"
		findlink $linklib;
	fi
}


# main function

if [ ! $# -eq "2" ]; then
	exit;
fi

if [ ! -e $2 ]; then
	exit;
fi

if [ ! -d $1 ]; then
	exit;
fi

bin=$2
rootfs=$1

debug "bin is $bin, rootfs is $rootfs"

ldd $bin | while read libs; do
	f1=`echo $libs | cut -d " " -f 1`;
	if echo $f1 | grep "^/" > /dev/null; then 
		lib=$f1;
	else
		f3=`echo $libs | cut -d " " -f 3`;
		if echo $f3 | grep "^/" > /dev/null; then 
			lib=$f3;
		else
			continue;
		fi
	fi

	debug "lib is $lib";

	findlink "$lib"

	debug ""
done


